package cn.aitstone.user.service.impl;

import cn.aitstone.basic.constant.BaseConstants;
import cn.aitstone.basic.dto.EmailCodeDto;
import cn.aitstone.basic.dto.SmsCodeDto;
import cn.aitstone.basic.exception.BusinessException;
import cn.aitstone.basic.utils.MD5Utils;
import cn.aitstone.basic.utils.StrUtils;
import cn.aitstone.basic.utils.VerifyCodeUtils;
import cn.aitstone.user.domain.Logininfo;
import cn.aitstone.user.domain.User;
import cn.aitstone.user.mapper.LogininfoMapper;
import cn.aitstone.user.mapper.UserMapper;
import cn.aitstone.user.service.IUserService;
import cn.aitstone.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sheldon
 * @since 2022-07-06
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
    * @Title: registerPhone
    * @Description: 通过手机号注册方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/6 21:09
    * @Parameters: [smsCodeDto]
    * @Return void
    */
    @Override
    @Transactional
    public void registerPhone(SmsCodeDto smsCodeDto) {
        String phone = smsCodeDto.getPhone();
        String password = smsCodeDto.getPassword();
        String confirmPassword = smsCodeDto.getConfirmPassword();
        String smsCodeValue = smsCodeDto.getSmsCodeValue();
        // 参数校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password) ||
        StringUtils.isEmpty(confirmPassword) || StringUtils.isEmpty(smsCodeValue)){
            throw new BusinessException("参数不能为空");
        }
        // 判断两次密码是否一致
        if (!password.equals(confirmPassword)){
            throw new BusinessException("两次密码不一致，请重新输入");
        }
        String smsCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + phone;
        Object smsCodeValueTemp = redisTemplate.opsForValue().get(smsCodeKey);
        if (smsCodeValueTemp == null){
            throw new BusinessException("验证码已过期，请重新获取");
        }

        String phoneCode = smsCodeValueTemp.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(smsCodeValue)){
            throw new BusinessException("验证码错误");
        }
        // 根据电话号码查询该用户
        User user = userMapper.loadByPhone(phone);
        if(user != null){
            throw new BusinessException("用户已存在，请直接登录");
        }

        user = smsCodeDto2User(smsCodeDto);
        // 保存user表
        userMapper.save(user);
        // 7.保存logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        // 8.将logininfo主键设置到user表，并修改
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);



    }

    /**
    * @Title: registerEmail
    * @Description: 通过邮箱注册
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/8 16:02
    * @Parameters: [emailCodeDto]
    * @Return void
    */
    @Override
    public void registerEmail(EmailCodeDto emailCodeDto) {
        String email = emailCodeDto.getEmail();
        String password = emailCodeDto.getPassword();
        String confirmPassword = emailCodeDto.getConfirmPassword();
        String emailCodeValue = emailCodeDto.getEmailCodeValue();
        // 参数校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(confirmPassword) || StringUtils.isEmpty(emailCodeValue)){
            throw new BusinessException("参数不能为空");
        }

        if (!password.equals(confirmPassword)){
            throw new BusinessException("两次密码不一致，请重新输入");
        }

        String emailCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + email;
        System.out.println(emailCodeKey);
        Object emailCodeValueTemp = redisTemplate.opsForValue().get(emailCodeKey);

        System.out.println(emailCodeValueTemp);
        if (emailCodeValueTemp == null){
            throw new BusinessException("验证码已过期，请重新获取");
        }

        String emailCode = emailCodeValueTemp.toString().split(":")[1];
        if (!emailCode.equalsIgnoreCase(emailCodeValue)){
            throw new BusinessException("验证码错误");
        }
        // 根据邮箱号查询该用户
        User user = userMapper.loadByEmail(email);
        if(user != null){
            throw new BusinessException("用户已存在，请直接登录");
        }
        user = emailCodeDto2User(emailCodeDto);
        // 保存user表
        userMapper.save(user);
        // 保存logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        // 将logininfo主键设置到user表，并修改
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
    }

    @Override
    public User loadByLogininfoId(Long logininfoId) {
        return userMapper.loadByLogininfoId(logininfoId);
    }

    private User emailCodeDto2User(EmailCodeDto emailCodeDto) {
        User user = new User();
        user.setUsername(emailCodeDto.getEmail());
        user.setEmail(emailCodeDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String saltpassword = MD5Utils.encrypByMd5(salt + emailCodeDto.getPassword());
        user.setSalt(salt);
        user.setPassword(saltpassword);
        return user;

    }

    /**
    * @Title: user2Logininfo
    * @Description: 将user对象中的值赋值给logininfo
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/6 21:09
    * @Parameters: [user]
    * @Return cn.aitstone.user.domain.Logininfo
    */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    /**
    * @Title: smsCodeDto2User
    * @Description: 将前端传递来的对象中的值对应地赋值给user
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/6 21:10
    * @Parameters: [smsCodeDto]
    * @Return cn.aitstone.user.domain.User
    */
    private User smsCodeDto2User(SmsCodeDto smsCodeDto) {
        User user = new User();
        user.setUsername(smsCodeDto.getPhone());
        user.setPhone(smsCodeDto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String saltpassword = MD5Utils.encrypByMd5(salt + smsCodeDto.getPassword());
        user.setSalt(salt);
        user.setPassword(saltpassword);
        return user;

    }
}
